What is https?
The 'https' npm package is a core Node.js module that provides an easy way to make HTTP requests over TLS/SSL. It is used to create HTTPS servers and clients, enabling secure communication over the web.
What are https's main functionalities?
Creating an HTTPS Server
This feature allows you to create an HTTPS server using SSL/TLS certificates. The server listens on port 443 and responds with 'Hello, Secure World!' to any incoming requests.
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, Secure World!');
}).listen(443);
Making HTTPS Requests
This feature allows you to make HTTPS GET requests to a specified URL. The example fetches a JSON object from 'jsonplaceholder.typicode.com' and logs it to the console.
const https = require('https');
https.get('https://jsonplaceholder.typicode.com/todos/1', (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
resp.on('end', () => {
console.log(JSON.parse(data));
});
}).on('error', (err) => {
console.log('Error: ' + err.message);
});
Other packages similar to https
axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple and easy-to-use API for making HTTP requests, including support for interceptors, automatic JSON transformation, and more. Compared to 'https', Axios offers a higher-level abstraction and additional features like request cancellation and automatic retries.
request
Request is a simplified HTTP client for Node.js, designed to be easy to use. It supports HTTPS and provides a wide range of features, including custom headers, cookies, and multipart form data. While 'request' is more feature-rich and user-friendly, it has been deprecated in favor of more modern alternatives like Axios.
node-fetch
Node-fetch is a lightweight module that brings the Fetch API to Node.js. It is designed to be a minimalistic and modern way to make HTTP requests, similar to the Fetch API available in browsers. Compared to 'https', node-fetch offers a more modern and familiar API for developers who are used to working with the Fetch API in the browser.